package controllers;

import models.User;
import others.Utils;
import play.data.validation.Email;
import play.data.validation.Required;

public class Accounts extends GameController {

	public static void register() {
		render();
	}

	public static void doRegister(@Email @Required String email) throws Throwable {
		if (validation.hasErrors()) {
			flash.error("Please supply a valid email address.");
			params.flash();
			register();
		}

		User user = User.find("byEmail", email).first();
		if (user != null) {
			flash.error("Email already exists, please try another.");
			params.flash();
			register();
		}

		String randomPassword = Utils.randomHash(4);
		user = new User();
		user.email = email;
		user.passwordHash = Utils.md5(randomPassword);
		user.save();
		// TODO email the password
		System.out.println("Password for " + email + ": " + randomPassword);
		flash.success("Successfully registered. Use the password emailed to you to login.");
		Secure.login();
	}
}
